package com.hmall.gateway.filter;

import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import lombok.RequiredArgsConstructor;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@RequiredArgsConstructor
public class LoginGlobalFilter implements GlobalFilter, Ordered {
    private final AuthProperties authProperties;
    private final JwtTool jwtTool;
    private  AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1、获取请求路径
        ServerHttpRequest request = exchange.getRequest();
        String currentRequestPath = exchange.getRequest().getPath().toString();

        //2、判断当前请求路径是否需要拦截，如果不需要，直接放行
        if (isAllowPath(currentRequestPath)){
            return chain.filter(exchange);
        }

        //3、拦截，从请求头中获取token
        String token = request.getHeaders().getFirst("Authorization");

        //4、解析token，获取其中的userId
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (Exception e) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //5、将userId像微服务传递（请求头中）
        //方式一
        String userIdStr = userId.toString();
//        ServerWebExchange webExchange = exchange.mutate().request(
//                r -> r.header("user-info", userIdStr)).build();
//        return chain.filter(webExchange);
        //方式二
        ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate().header("user-info", userIdStr).build();
        return chain.filter(exchange.mutate().request(serverHttpRequest).build());

    }
    /**
     * 判断当前请求路径是否需要拦截
     * @param currentRequestPath
     * @return
     */
    private boolean isAllowPath(String currentRequestPath) {
        for (String excludePath : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(excludePath, currentRequestPath)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
